import os
from datetime import datetime

from wtforms import ValidationError

from common.json_util import to_dicts
from common.oss_upload import get_file_url
from config import config_settings
from daos.video_library_dao import *
from models.biz_enum import SystemLogModule, VideoLibraryDySyncStatus, VideoLibraryStatus, VideoLibraryOssStatus
from rules import db_commit, PAGINATION_PAGE_SIZE
from rules.system_log_rule import create_system_log


def search_video_library(pk):
    result = query_video_library(pk)
    return result


def search_video_library_by_title(title):
    result = query_video_library_by_title(title)
    return result


def search_video_library_with_page(page_index, data_param):
    data_param['page'] = page_index
    data_param['page_size'] = PAGINATION_PAGE_SIZE
    result = query_video_library_with_page(data_param)
    item_dicts = to_dicts(result.items)
    for item in item_dicts:
        item["oss_status_name"] = VideoLibraryOssStatus.get_name(item.get("oss_status"))
    result.items = item_dicts
    return result


def search_video_library_with_list(data_param):
    if not data_param.get('status'):
        data_param['status'] = VideoLibraryStatus.NORMAL.value

    result = to_dicts(query_video_library_s(data_param))
    for item in result:
        item['file_url'] = get_file_url(item.get('file_name'), expires=600)
    return result


def create_video_library(form, current_user):
    is_commit = False

    video_library_orm = VideoLibrary()

    video_library_orm.title = form.title.data
    video_library_orm.file_name = form.file_name.data
    video_library_orm.temp_file_name = form.temp_file_name.data
    video_library_orm.oss_status = VideoLibraryOssStatus.WAIT.value
    video_library_orm.dy_sync_status = VideoLibraryDySyncStatus.WAIT_COMMIT.value
    video_library_orm.dy_open_video_id = ''
    video_library_orm.status = VideoLibraryStatus.NORMAL.value
    video_library_orm.remarks = form.remarks.data

    result = add_video_library(video_library_orm, is_commit)

    # 添加系统日志
    operation_detail_dict = dict(before_operation=None, after_operation=video_library_orm.to_dict())
    log_dict = dict(module=SystemLogModule.CREATE_VIDEO_LIBRARY.value, operation_detail=operation_detail_dict,
                    operator=current_user.id)
    create_system_log(log_dict, is_commit)

    # 异步提交上传视频任务
    from apps import tasks
    image_absolute_path = os.path.abspath(
        os.path.join(config_settings.VIDEO_UPLOAD_FOLDER, video_library_orm.temp_file_name))
    task = tasks.async_upload_video.delay(video_library_orm.file_name, image_absolute_path)
    print(f"up_result:{task}")

    if not is_commit:
        db_commit()

    return result.to_dict()


def describe_video_library(pk, form, current_user):
    is_commit = False
    now = datetime.now()
    video_library_orm = query_video_library(pk)
    if video_library_orm:
        before_operation = video_library_orm.to_dict()

        need_update_list = ["last_update_time"]
        if form.title.data != video_library_orm.title:
            c = query_video_library_count(dict(title=form.title.data))
            if c > 0:
                raise ValidationError('标题已存在')

            video_library_orm.title = form.title.data
            need_update_list.append("title")

        if form.remarks.data != video_library_orm.remarks:
            video_library_orm.remarks = form.remarks.data
            need_update_list.append("remarks")

        video_library_orm.last_update_time = now

        update_video_library(video_library_orm, *need_update_list, is_commit=is_commit)

        # 添加系统日志
        operation_detail_dict = dict(before_operation=before_operation, after_operation=video_library_orm.to_dict())
        log_dict = dict(module=SystemLogModule.UPDATE_VIDEO_LIBRARY, operation_detail=operation_detail_dict,
                        operator=current_user.id)
        create_system_log(log_dict, is_commit)

        if not is_commit:
            db_commit()

    return


def describe_video_library_oss_status(file_name, up_result):
    video_library_orm = query_video_library_by_file_name(file_name)
    if video_library_orm:
        video_library_orm.oss_status = VideoLibraryOssStatus.SUCCESS.value if up_result.get(
            'status') == 200 else VideoLibraryOssStatus.FAIL.value

        need_update_list = ["last_update_time"]
        update_video_library(video_library_orm, *need_update_list)

    return
